import React, { useState, useEffect } from "react";
import { Button, Input, Form, Cascader, message } from 'antd';
import $ from 'jquery';
import intl from 'react-intl-universal';

const { SHOW_CHILD } = Cascader;


const SearchBar = (props) => {
    const [tempData, setTempData] = useState([]);             // 后端接收数据
    const [classifyData, setClassifyData] = useState([]);     // 处理后的分类数据
    const [handleData, setHandleData] = useState(false);      // 是否处理tempData

    // 获取后台数据
    const [hasChange, setHasChange] = useState(true);
    useEffect(() => {
        const getClassification = () => {
            $.ajax({
                url: '/home/classify',
                type: 'post',
                dataType: 'json',
                success: function (result) {
                    if (result.status === 1) {
                        setTempData(result.data);
                        setHandleData(true);
                    } else {
                        message.info(intl.get('failedToQuery'));
                    }
                },
                error: function (err) {
                    alert(JSON.stringify(err));
                },
            });
        };
        hasChange && getClassification();
        setHasChange(false);
    }, [hasChange]);


    // 处理从后端接收的数据，成树形结构
    const createTree = (data) => {
        let treeData = [];
        // 获取一级节点
        let roots = data.filter(element => element.parent === 0);
        treeData.push(...roots);
        // 从一级节点开始，获取每个元素的子元素放到该元素的children属性中
        const getChildren = (result, data) => {
            result.forEach((element, index) => {
                element.children = data.filter((item, index) => item.parent === element.kid);
                if (element.children.length > 0) {
                    getChildren(element.children, data);
                }
            });
        }
        getChildren(treeData, data);
        return treeData;
    };


    // 再次处理数据，成官方文档中treeData格式
    const createTreeData = (data) => {
        let treeData = [];
        data.map((item) => {
            let node = {
                key: item.kid,
                label: item.kname,
                value: item.kname,
                children: createTreeData(item.children),
                parent: item.parent,
            };
            treeData.push(node);
        });
        return treeData;
    };


    // 调用处理数据的方法
    useEffect(() => {
        let treeData = [];
        if (handleData) {
            treeData = createTree(tempData);
            treeData = createTreeData(treeData);
            setClassifyData(treeData);
        }
        setHandleData(false);
    }, [handleData]);


    // 搜索
    const onFinish = (value) => {
        // console.log('query', value)
        let kindArr = value.kind;
        if (kindArr !== undefined && kindArr !== null)
            value.kind = kindArr[kindArr.length - 1];
        $.ajax({
            url: '/home/article',
            type: 'post',
            data: value,
            traditional: true,
            dataType: 'json',
            success: function (result) {
                props.callback(result.data)
            },
            error: function (err) {
            }
        });
    };


    return (
        <Form layout={'inline'} onFinish={onFinish}>
            <Form.Item name={'kind'} className='cascaderOnSearch'>
                <Cascader options={classifyData} multiple={false} maxTagCount="responsive" showCheckedStrategy={SHOW_CHILD} placeholder={intl.get('kind')} />
            </Form.Item>
            <Form.Item name={'author'} className='usernameOnSearch'>
                <Input placeholder={intl.get('author')} allowClear={true} />
            </Form.Item>
            <Form.Item name={'title'} className='nameOnSearch'>
                <Input placeholder={intl.get('title')} allowClear={true} />
            </Form.Item>
            <Form.Item style={{ width: '50px' }} className='submitOnSearch'>
                <Button type="primary" htmlType="submit">{intl.get('search')}</Button>
            </Form.Item>
        </Form>
    );
};

export default SearchBar;